#include <jni.h>
#include <android_native_app_glue.h>
#include <android/log.h>
#include "../../ge_internal.h"

#define LOGW(...) ((void)__android_log_print(ANDROID_LOG_WARN, "GE_JNI", __VA_ARGS__))

ge_File* geJniOpenFd(JNIEnv* env, jobject fd, jint ofs, jint len);
extern JavaVM* vm;
extern struct android_app state;

static bool GEFont_initialized = false;
static jclass jGEFont = (void*)NULL;
static jfieldID font_ptr_id = (void*)-1;
static jfieldID font_ptr_size = (void*)-1;

void GEFont_init(JNIEnv* env){
	jGEFont = (*env)->FindClass(env, "com/ssp/libge/GEFont");
	font_ptr_id = (*env)->GetFieldID(env, jGEFont, "_ptr", "I");
	font_ptr_size = (*env)->GetFieldID(env, jGEFont, "size", "I");
	GEFont_initialized = true;
}

void Java_com_ssp_libge_GEFont_Load(JNIEnv* env, jobject this, jstring jfilename){
	if(!GEFont_initialized){
		GEFont_init(env);
	}

	const char* filename = (*env)->GetStringUTFChars(env, jfilename, NULL);
	ge_Font* font = geLoadFont(filename);
	(*env)->ReleaseStringUTFChars(env, jfilename, filename);

	(*env)->SetIntField(env, this, font_ptr_id, (jint)font);
	(*env)->SetIntField(env, this, font_ptr_size, (jint)font->size);
}

void Java_com_ssp_libge_GEFont_Loadid(JNIEnv* env, jobject this, jobject jfd, jlong ofs, jlong len){
	if(!GEFont_initialized){
		GEFont_init(env);
	}

	ge_File* file = geJniOpenFd(env, jfd, ofs, len);
	if(file){
		ge_Font* font = geLoadFont(gePathFromFile(file));
		(*env)->SetIntField(env, this, font_ptr_id, (jint)font);
		(*env)->SetIntField(env, this, font_ptr_size, (jint)font->size);
	}
}

void Java_com_ssp_libge_GEFont_LoadSystem(JNIEnv* env, jobject this){
	if(!GEFont_initialized){
		GEFont_init(env);
	}

	ge_Font* font = geLoadFont("");

	(*env)->SetIntField(env, this, font_ptr_id, (jint)font);
	(*env)->SetIntField(env, this, font_ptr_size, (jint)font->size);
}

void Java_com_ssp_libge_GEFont_setSize(JNIEnv* env, jobject this, jint size){
	if(!GEFont_initialized){
		GEFont_init(env);
	}

	ge_Font* font = (ge_Font*)(*env)->GetIntField(env, this, font_ptr_id);
	if(font){
		geFontSize(font, size);
		(*env)->SetIntField(env, this, font_ptr_size, (jint)font->size);
	}
}

void Java_com_ssp_libge_ge_Print(JNIEnv* env, jobject this, jint x, jint y, jobject jfont, jint color, jstring jtext){
	ge_Font* font = (ge_Font*)(*env)->GetIntField(env, jfont, font_ptr_id);
	if(font){
		const char* text = (*env)->GetStringUTFChars(env, jtext, NULL);
		geFontPrintScreen(x, y, font, text, color);
		(*env)->ReleaseStringUTFChars(env, jtext, text);
	}
}
